﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using Apps.Yunwei.Views;
using Apps.Yunwei.YunWeiService;
using Microsoft.Expression.Interactivity.Core;
using QDP.Platform.Services;
using QDP.Platform.Silverlight;
using QDP.Platform.Silverlight.Aware;

namespace Apps.Yunwei.ViewModels
{
    public class RolesViewModel : INotifyPropertyChanged,IRefreshAware
    {
        public ICommand AddCommand { get; private set; }
        public ICommand EditCommand { get; private set; }
        public ICommand DeleteCommand { get; private set; }
        public ObservableCollection<RoleObject> Items { get; set; }
        private string URL { get; set; }
        private Dictionary<string, string> configs;
        private YunWeiService.RoleObject objectInfo;

        private string UserID;

        public RolesViewModel()
        {
            this.Items = new ObservableCollection<YunWeiService.RoleObject>();
            this.AddCommand = new ActionCommand(this.AddContact);
            this.EditCommand = new ActionCommand(this.EditContact);
            this.DeleteCommand = new ActionCommand(this.DeleteContact);
        }
        public void SetConfig(Dictionary<string, string> cfgs)
        {
            this.configs = cfgs;
            URL = configs["CC_URL"];
            this.Initialize();
            this.Refresh();
        }
        NorOpSvClient Client = null;
        private void Initialize()
        {
            var user = Q.DataManager.GetUserData() as Identity;
            UserID = user.ID;

            Client = ServiceLoader.CreateWCFClient<NorOpSvClient>(URL);
            Client.DeleteRoleCompleted += Client_DeleteRoleCompleted;
            Client.GetRolesCompleted += client_GetRolesCompleted;
            Client.InsertRoleCompleted += Client_InsertRoleCompleted;
            Client.UpdateRoleCompleted += Client_UpdateRoleCompleted;
        }
        void client_GetRolesCompleted(object sender, GetRolesCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                this.ShowMessage(e.Error.Message,e.Error.ToString());
                return;
            }
            this.Items.Clear();

            var objects = e.Result;

            foreach (var v in objects.OrderBy(p => p.Code))
            {
                this.Items.Add(v);
            }
        }

        void Client_UpdateRoleCompleted(object sender, UpdateRoleCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                this.ShowMessage(e.Error.Message,e.Error.ToString());
                return;
            }
            if (e.Result.IsSuccess == false)
            {
                this.ShowMessage("操作失败",e.Result.Message);
            }
            else
            {
                int i = this.Items.IndexOf(objectInfo);
                this.Items.RemoveAt(i);
                this.Items.Insert(i, objectInfo);
            }
        }

        void Client_InsertRoleCompleted(object sender, InsertRoleCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                this.ShowMessage(e.Error.Message,e.Error.ToString());
                return;
            }
            if (e.Result.IsSuccess == false)
            {
                this.ShowMessage("操作失败" , e.Result.Message);
            }
            else
            {
                this.Items.Add(objectInfo);
            }
        }

        void Client_DeleteRoleCompleted(object sender, DeleteRoleCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                this.ShowMessage(e.Error.Message,e.Error.ToString());
                return;
            }
            if (e.Result.IsSuccess == false)
            {
                this.ShowMessage("操作失败" ,e.Result.Message);
            }
            else
            {
                this.Items.Remove(objectInfo);
            }
        }

        public void AddContact()
        {
            objectInfo = new RoleObject();
            this.EditContact(objectInfo, dialogResult =>
            {
                if (dialogResult.HasValue && dialogResult.Value)
                {
                    objectInfo.ID = Guid.NewGuid().ToString();
                    Client.InsertRoleAsync(objectInfo);
                }
            });
        }

        public void EditContact(object selectedItem)
        {
            objectInfo = (RoleObject)selectedItem;

            this.EditContact(objectInfo, dialogResult =>
            {
                if (dialogResult.HasValue && dialogResult.Value)
                {
                    Client.UpdateRoleAsync(objectInfo);
                }
            });
        }

        private void EditContact(object selectedItem, Action<bool?> finishedCallback)
        {
            var detailWindow = new RoleDetail();
            detailWindow.DataContext = selectedItem;
            detailWindow.Show();
            if (finishedCallback != null)
            {
                detailWindow.Closed += (o, e) =>
                {
                    finishedCallback(detailWindow.DialogResult);
                };
            }
        }

        public void DeleteContact(object selectedItem)
        {
            objectInfo = (RoleObject)selectedItem;
            if (MessageBox.Show("确定删除用户[" + objectInfo.Caption + "]信息？", string.Empty, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                Client.DeleteRoleAsync(objectInfo.ID);
            }
        }

        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
        #endregion

        #region IRefreshAware 成员

        public void Refresh()
        {
            Client.GetRolesAsync();
        }

        #endregion
    }
}
